<template>
	<view class="settlementCenter-box">
		
		<!-- 收货地址模块 -->
		<uni-card class="shippingAddress-seaction" :is-shadow="false" :is-full="true" :border="false">
			<!-- 未添加地址视图 -->
			<view class="no-address" v-if="true" @click="toAddShippingAddress">
				<text><text class="new-mask">#</text>点击添加收货信息</text>
				<uni-icons type="location" size="22"></uni-icons>
			</view>
			<!-- 地址列表视图 -->
			<view class="has-address" v-if="selectedAddress" @click="toAddShippingAddress">
				<view class="ask-info">
					<text>联系信息:</text>
					<text>{{ selectedAddress.userName }}</text>
					<text>{{ selectedAddress.userPhone }}</text>
				</view>
				<view class="ask-address">
					<text>收货地址:</text>
					<text>{{ selectedAddress.userAddress }}</text>
				</view>
				<uni-icons class="forward-link" type="forward" size="22"></uni-icons>
			</view>
		</uni-card>

		<uni-card class="store-view" :is-shadow="false" :border="false">
			<view class="store-seaction" v-for="(good, index) in goods.data" :key="good.goodsId">
				<view class="store-img">
					<img :src="picBaseUrl + good.picUrl" alt="">
				</view>
				<view class="store-info">
					<text class="store-secondName">{{ '高端定制' }}</text>
					<view>
						<view class="location">
							<view class="local-item">{{ good.subFourthName }}</view>
						</view>
						<text class="store-price">￥{{ good.price }}</text>
					</view>
					<view class="count">
						<text :style="{color: good.quantity === 1 ? '#ccc': '#444'}" class="text"
							@tap.prevent.stop="reduceShopCar(index, good.fourthId)">-</text>
						<view class="input">{{ good.quantity }}</view>
						<text class="text" @tap.prevent.stop="addShopCar(index, good.goodsId)">+</text>
					</view>
				</view>
			</view>
		</uni-card>
		
		<!-- 服务类型 -->
		<uni-card class="service-type" :is-shadow="false" :border="false" :is-full="true">
			<uni-section title="选择服务类型" type="line"></uni-section>
		</uni-card>
		<uni-card class="serviceSelected-list" :is-shadow="false" :border="false" :is-full="true">
			<view class="service-item">
				<view :class="{'item': true, 'item__actived': activedName === 'daodian'}"
					@click="activedService('daodian')">
					<image src="@/static/icons/follow-shop.png"></image>
					<text>到店服务</text>
				</view>
				<view :class="{'item': true, 'item__actived': activedName === 'shunfeng'}"
					@click="activedService('shunfeng')">
					<image src="@/static/icons/follow-shunfeng.png"></image>
					<text>顺丰上门</text>
				</view>
			</view>
		</uni-card>
		
		<!-- 选择体验店 -->
		<uni-card class="select-shop" :is-shadow="false" :border="false" :is-full="true">
			<uni-section title="选择体验店" type="line"></uni-section>
			<view class="detail-info">
				<text>北京SKP店 177-1060-3595</text>
				<text>北京市朝阳区西大望路甲6号(大望路地铁站F东北口步行290米)华贸公寓内（SKP紧北侧）</text>
				<uni-icons class="uniIcons" type="forward" size="22"></uni-icons>
			</view>
		</uni-card>
		
		<!-- 留言模块 -->
<!-- 		<uni-card class="message-box" :is-shadow="false" :border="false" :is-full="true">
			<text>留言备注</text>
			<textarea :value="messageValue" placeholder="您还有什么需求,请留言告诉我们"></textarea>
		</uni-card> -->
		<uni-card class="message-box" :is-shadow="false" :border="false" :is-full="true">
			<text>留言备注</text>
			<textarea v-model="messageValue" placeholder="您还有什么需求,请留言告诉我们"></textarea>
		</uni-card>
		
		<!-- 上传照片 -->
		<uni-card class="clothes-photo" :is-shadow="false" :border="false" :is-full="true">
			<text>上传衣物照片</text>
			<view class="photo-item">
				<uni-file-picker ref="files" limit="8" :autoUpload="false" @select="selectAfter" @fail="uploadFail" />
				<template v-for="(pic, index) in imageValue" :key="pic.uuid">
					<view class="photos" v-show="index <= 2">
						<uni-icons v-if="!pic.url" class="camera" type="camera" @click="mockUpload(index)"></uni-icons>
						<image v-else :src="pic.url"></image>
						<view class="close-icon" v-show="pic.url" @click.prevent.stop="deletePhotos(index)">x</view>
					</view>
				</template>
			</view>
		</uni-card>
	</view>
	
	<!-- 提交订单 -->
	<uni-card class="submit-box" :is-shadow="false" :border="false" :is-full="true">
		<view class="submitOrder">
			<text>合计: ￥{{ amount.valueOf() }}</text>
			<view class="submit-right">
				<text>应付: ￥{{ amount.valueOf() }}</text>
				<button class="btn" @tap.prevent.stop="submitOrder">提交订单</button>
			</view>
		</view>
	</uni-card>
</template>

<script setup lang="ts">
	import { reactive, ref, shallowReactive } from "vue"
	import { onLoad } from '@dcloudio/uni-app'
	import { Shop } from "@/api/types/Shop"
	import { orderSettlement, createOrder } from '@/api/http/settlementCenter'
	import { SettlementCenter } from '@/api/types/settlementCenter'
	import { picBaseUrl } from '@/api/request'
	import { addShopNum, listShopCar, reduceShopNum } from "@/api/http/shopCar"
	import { onMounted, onUnmounted } from 'vue';
	import { userAddress } from '@/api/types/userAddress';
	import { computed } from 'vue';
	
	/**
	 * computed 是 Vue 提供的一个响应式计算属性，可以根据依赖的值自动更新
	 */
	const amount = computed(() => {
	    return goods.data.reduce((total, item) => total + item.price * item.quantity, 0);
	});
	
	const userId = uni.getStorageSync('userId');
	const selectedAddress = ref<userAddress.userAddressType>();
	
	
	onMounted(() => {
	    // 监听返回的地址数据
	    uni.$on('addressSelected', (address) => {
	        selectedAddress.value = address;  // 将接收到的地址数据赋给 selectedAddress
			console.log('selectedAddress:', selectedAddress.value);
	    });
	});
	
	onUnmounted(() => {
	    // 清理事件监听
	    uni.$off('addressSelected');
	});
	
	/**
	 * useTo:   留言模块
	 */
	let messageValue = ref<string>('')

	/**
	 * useTo:   上传图片
	 */
	let files = ref()
	let imageValue = ref<Array<any>>([{ url: '' }])
	const mockUpload = (i : number) => {
		files.value?.choose()
		recordCurrentIndex.value = i
	}
	let recordCurrentIndex = ref<number>()
	const selectAfter = (files : any) => {
		imageValue.value.splice(recordCurrentIndex.value, 0, ...files.tempFiles)
	}
	const deletePhotos = (i : number) => {
		imageValue.value.splice(i, 1)
	}
	const uploadFail = (err) => {
		let arr = err.errMsg.split(':')
		uni.showToast({
			title: arr[1],
			icon: 'error'
		})
	}
	/**
	 * useTo: 跳转到添加收货地址路由 
	 */
	const toAddShippingAddress = () => {
		uni.navigateTo({
			url: '/pages/components/n-userAddress'
		})
	}
	/**
	 * useTo: 跳转到地址列表路由 
	 */
	const toShippingAddressList = () => {
		uni.navigateTo({
			url: '/pages/components/n-shippingAddressList'
		})
	}

	/**
	 * useTo: 激活服务类型 
	 */
	let activedName = ref<string>('')
	const activedService = (active : string) => {
		activedName.value = active
	}

	/**
	 * @description 加载页面，获取路由传递过来的参数 ,加载指定id下的商品信息被做后续订单操作
	 */
	let selectedGoods = shallowReactive<{ ids : number[] }>({
		ids: []
	})
	
	/**
	 * @description 获取订单详情信息 
	 */
	const goods = reactive<{ data : SettlementCenter.orderInfoType[] }>({
		data: []
	})
	onLoad(async (option) => {
		console.log("option",option)
		selectedGoods.ids = JSON.parse(decodeURIComponent(option.goodIds));
		console.log("selectedGoods.ids",selectedGoods.ids)
		goods.data = await orderSettlement(selectedGoods.ids, userId)
		console.log("amount",amount.value)
		console.log("goods",goods.data)
	})
    // let amount =goods.data.reduce((total, item) => total + item.price * item.quantity, 0);
	
	/**
	 * useTo: 控制计数器
	 */
	const reduceShopCar = async (index : number, id : number) => {
		if (goods.data[index].quantity <= 1) return;
		await reduceShopNum({ userId: userId, goodId: id })
		await orderSettlement([id], userId)
	}
	const addShopCar = async (index : number, id : number) => {
		await addShopNum({ userId: userId, goodId: id })
		await orderSettlement([id], userId)
	}

	/**
	 * @description 提交订单
	 */
	const submitOrder = () => {
		console.log(messageValue.value, 'xxx');
		uni.request(
		{
			url: 'https://sxg123.cn/ignore/user/order/createOrder',
			method: 'POST',
			dataType: 'json',
			header: {
				'content-type': 'application/json;charset=UTF-8;'
			},
			data: {
				"goodsIds": goods.data.map((item) => item.goodsId),
				"orderExplain": messageValue.value, 					// 留言
				"serviceType": activedName.value === 'daodian' ? 1 : 2, // 服务类型
				"storeId": 1,											// 目前只有一个店，华贸店
				"totalAmount": goods.data.reduce((total, item) => total + item.price * item.quantity, 0), // 总金额
				"userAddress": selectedAddress.value.userAddress, 		// 收货地址
				"userPhone": selectedAddress.value.userPhone,			// 用户手机
				"userName": selectedAddress.value.userName,				// 用户名字
				"userId": userId
			},
            success(res) {
                console.log(res, '订单创建成功');
				console.log("==========",selectedAddress.value)
				console.log("xxxxxxxxxxxxxxxxxxxxxxxx",encodeURIComponent(JSON.stringify(selectedAddress.value)))
                // 将订单号和其他必要数据通过路由传递到支付页面
                uni.navigateTo({
                    url: `/pages/components/weChatPay?orderNumber=${res.data}&totalAmount=${amount.value*100}}`
                });
            }
		}
		)
	}
	
</script>

<style scoped lang="scss">
	.settlementCenter-box {
		padding-top: 35rpx;
		padding-bottom: 100rpx;

		// 收货信息部分
		.shippingAddress-seaction {

			// 添加地址的盒子
			.no-address,
			.has-address {
				padding: 10rpx 0 !important;
				box-sizing: border-box;
			}

			.no-address {
				@include flex;

				.new-mask {
					margin-right: 15rpx;
					font-size: 30rpx;
					color: $uni-primary;
				}
			}

			//  有详细地址的盒子
			.has-address {
				position: relative;
				width: 100%;

				.ask-info,
				%askAddress {
					height: 30rpx;
					line-height: 30rpx;
					color: $uni-main-color;

					text {
						&:nth-child(2) {
							padding: 0 20rpx;
							color: $uni-base-color;
						}
					}
				}

				.ask-address {
					@include ellipsis;
					@extend %askAddress;
					margin-top: 20rpx;
				}

				.forward-link {
					position: absolute;
					bottom: 40rpx;
					right: 0rpx;
				}
			}
		}

		// 商品展示区
		.store-view {
			:deep(.uni-card) {
				margin: 20rpx 0 !important;
			}

			.store-seaction {
				display: flex;

				.store-img {
					position: relative;
					width: 180rpx;
					height: 180rpx;
					border-radius: 50%;
					border: 1px solid #dfdfdf;
					box-sizing: border-box;
					overflow: hidden;

					image {
						@include domCenter;
						width: 50%;
						height: 70%;
					}
				}

				.store-info {
					position: relative;
					display: flex;
					flex-direction: column;
					justify-content: space-between;
					margin-left: 30rpx;
					padding: 10rpx 0;
					width: calc(100vw - 270rpx);
					box-sizing: border-box;

					text {
						@include ellipsis;
						height: 30rpx;
						line-height: 30rpx;
						font-size: 28rpx;
					}

					.location {
						display: flex;
						flex-wrap: wrap;
						margin-bottom: 20rpx;
						height: 30rpx;
						line-height: 30rpx;
						font-size: 20rpx;

						.local-item {
							margin-right: 10rpx;
							margin-bottom: 10rpx;
							padding: 2rpx 20rpx;
							border-radius: 40rpx;
							background: rgba(0, 0, 0, .1);

							&:last-child {
								margin-right: 0;
							}
						}
					}

					.count {
						position: absolute;
						bottom: 20rpx;
						right: 20rpx;

						display: flex;
						justify-content: space-between;
						align-items: center;
						width: 220rpx;
						height: 48rpx;

						.text {
							height: 100%;
							padding: 0 20rpx;
							font-size: 32rpx;
							color: #444;
							background-color: #f6f6f6;
						}

						.input {
							flex: 1;
							height: 48rpx;
							text-align: center;
							line-height: 48rpx;
							border-radius: 4rpx;
							font-size: 24rpx;
							color: #444;
							border-left: 2px solid #fff;
							border-right: 2px solid #fff;
							background-color: #f6f6f6;
						}
					}
				}
			}
		}
	}

	// uni-card 公共样式
	%common {
		:deep(.uni-card) {
			padding: 0 !important;
			border-bottom: 1px solid $uni-border-3;
		}
	}

	// 服务类型
	.service-type {
		display: flex;
		flex-direction: column;
		@extend %common;
	}

	:deep(.uni-section) {
		.uni-section-header__decoration {
			width: 8rpx !important;
			height: 30rpx !important;
		}

		.uni-section-header__content {
			.uni-section__content-title {
				height: 30rpx;
				line-height: 30rpx;
				font-size: 28rpx !important;
				font-weight: 700;
			}
		}
	}

	// 宫格样式
	.serviceSelected-list {
		@extend %common;

		.service-item {
			display: flex;
			justify-content: center;
			align-items: center;

			.item {
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;
				margin-right: 20rpx;
				padding: 15rpx 60rpx;
				border-radius: 20rpx;
				background: rgba(0, 0, 0, .1);

				&:last-child {
					margin-right: 0;
				}

				image {
					margin-bottom: 20rpx;
					width: 90rpx;
					height: 90rpx;
				}
			}

			.item__actived {
				background: $uni-primary-disable;
			}
		}
	}

	// 选择体验店
	.select-shop {
		:deep(.uni-card) {
			padding: 0 !important;
		}

		.detail-info {
			position: relative;
			box-sizing: border-box;
			padding: 20rpx;
			@include columnFlex;

			text {
				&:first-child {
					margin-bottom: 10rpx;
				}
			}

			.uniIcons {
				position: absolute;
				top: 18rpx;
				right: 15rpx;
			}
		}
	}

	// 留言
	.message-box {
		:deep(.uni-card) {
			margin-top: 10rpx !important;
			border-bottom: 1px solid $uni-border-3;
		}

		text {
			font-size: 28rpx !important;
		}

		textarea {
			width: 100% !important;
			margin-top: 10rpx !important;
		}
	}

	// 上传照片
	.clothes-photo {
		text {
			font-size: 28rpx !important;
		}

		.photo-item {
			display: flex;
			padding-bottom: 50rpx;

			.photos {
				position: relative;
				margin-top: 20rpx;
				margin-right: 15rpx;
				transform: all 0.2s linear;

				&:last-child {
					margin-right: 0;
				}

				width: 20%;
				height: 100rpx;
				border-radius: 20rpx;
				border: 1px dashed $uni-primary;
				text-align: center;
				line-height: 100rpx;

				image {
					width: 100%;
					height: 100%;
					overflow: hidden;
					border-radius: inherit;
				}

				.close-icon {
					position: absolute;
					top: -10rpx;
					right: -10rpx;
					width: 30rpx;
					height: 30rpx;
					line-height: 30rpx;
					text-align: center;
					background: rgba(0, 0, 0, .5);
					border-radius: 50%;
					color: #fff
				}
			}
		}

		:deep(.uni-file-picker) {
			display: none !important;
		}
	}

	// 选择照片字体图标
	:deep(.camera) {
		text {
			font-size: 100rpx !important;
			color: $uni-primary !important;
		}
	}

	// 提交订单
	.submit-box {
		position: fixed;
		left: 0;
		bottom: 0;
		width: 100% !important;
		box-shadow: 0 -2px 10px #dfdfdf !important;

		.submitOrder {
			@include flex;
			align-items: center;

			.submit-right {
				display: flex;
				align-items: center;

				text {
					color: red;
				}

				.btn {
					margin-left: 20rpx;
					border-radius: 40rpx;
					color: #fff;
					letter-spacing: 2px;
					background-color: $uni-primary;
				}
			}
		}
	}
</style>